<!--
 * @Descripttion: 课堂分析详情-学生行为-行为动作
 * @version: V1.0.0.1
 * @Author: zhaozhenzhuo
 * @Date: 2025-10-29 14:52:41
 * @LastEditors: zhaozhenzhuo
 * @LastEditTime: 2025-10-29 14:52:41
-->
<template>
	<div class="behavior-action-wrapper">
		<div class="module-title-wrapper">
			<p>行为动作</p>
			<img v-if="false" src="@/assets/images/lessonAnalysisDetails/text-edit-normal.png" />
		</div>
		<div class="behavior-rate">
			<div class="little-title">
				<p>学生行为占比</p>
			</div>
			<div class="chart-wrap">
				<div class="pie-chart-wrap">
					<div class="title-wrap">
						<div class="line"></div>
						<p>学生行为占比</p>
					</div>
					<div
						v-if="
							(AILessonBehaviorStat?.readAndWrite?.rate ||
								AILessonBehaviorStat?.read?.rate ||
								AILessonBehaviorStat?.write?.rate ||
								AILessonBehaviorStat?.normal?.rate ||
								AILessonBehaviorStat?.hand?.rate ||
								AILessonBehaviorStat?.stand?.rate ||
								AILessonBehaviorStat?.sleep?.rate ||
								AILessonBehaviorStat?.phone?.rate ||
								AILessonBehaviorStat?.test?.rate ||
								AILessonBehaviorStat?.bowingTheHead?.rate ||
								AILessonBehaviorStat?.turnBack?.rate) &&
							!hideAll
						"
						class="pie-chart"
					></div>
					<p v-else class="empty">
						<span class="empty-wrap">本堂课未识别到学生行为</span>
					</p>
				</div>
				<div class="bar-chart-wrap">
					<div class="title-wrap">
						<div class="line"></div>
						<p>学生行为次数</p>
					</div>
					<div
						v-if="
							(AILessonBehaviorStat?.readAndWrite?.rate ||
								AILessonBehaviorStat?.read?.num ||
								AILessonBehaviorStat?.write?.num ||
								AILessonBehaviorStat?.normal?.num ||
								AILessonBehaviorStat?.hand?.num ||
								AILessonBehaviorStat?.stand?.num ||
								AILessonBehaviorStat?.sleep?.num ||
								AILessonBehaviorStat?.phone?.num ||
								AILessonBehaviorStat?.test?.num ||
								AILessonBehaviorStat?.bowingTheHead?.rate ||
								AILessonBehaviorStat?.turnBack?.rate) &&
							!hideAll
						"
						class="bar-chart"
					></div>
					<p v-else class="empty">
						<span class="empty-wrap">本堂课未识别到学生行为</span>
					</p>
				</div>
			</div>
		</div>
		<div class="behavior-trend">
			<div class="little-title">
				<p>学生课堂行为走势</p>
			</div>
			<div
				v-if="lessonBehaviorDetail && lessonBehaviorDetail.length && !hideAll"
				class="trend-chart-container"
			>
				<!-- echarts容器 -->
				<div class="trend-chart"></div>

				<!-- 休息时间标记线叠加层 -->
				<div
					v-for="(marker, index) in breakTimeMarkers"
					:key="index"
					class="break-time-marker"
					:style="{
						left: marker.left + 'px',
						top: marker.top + 'px',
						height: marker.height + 'px'
					}"
				>
					<div class="marker-label" :style="{ top: marker.labelTop + 'px' }">
						{{ marker.label }}
					</div>
				</div>
			</div>
			<p v-else class="empty">
				<span class="empty-wrap">本堂课未识别到学生行为</span>
			</p>
		</div>
	</div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { ref, watch, nextTick, computed, onMounted, shallowRef, onUnmounted } from 'vue';
import type {
	CourseListItemType,
	LessonBehaviorDetailItemType,
	NodeListType,
	AILessonBehaviorStatType,
	BehaviorStatItemType,
	NodeKeyType,
	BehaviorDataItemType,
	PreviewInfoType,
	BreakTimeMarker
} from './BehaviorAction.type';
import { getErrorMessage, getAILessonBehaviorStatAPI } from '@/api/index';
import { roundArrayWithSum } from '@/assets/js/utils';

const props = withDefaults(
	defineProps<{
		lessonInfo: CourseListItemType | null;
		lessonBehaviorDetail: LessonBehaviorDetailItemType[] | null;
		stepTime: number;
		videoBeginTime: number;
		configInfo: Record<string, unknown> | null;
		realBreakTimeArr: Array<{ startTime: number; endTime: number }> | null;
	}>(),
	{
		lessonInfo: null,
		lessonBehaviorDetail: () => [],
		stepTime: 5,
		videoBeginTime: 0,
		configInfo: null,
		realBreakTimeArr: null
	}
);

const emit = defineEmits<{
	(e: 'previewShow', info: PreviewInfoType): void;
}>();

// 模块配置项
const configList = computed<NodeListType | null>(
	() =>
		((props.configInfo?.studentBehavior as Record<string, unknown>)?.nodeList as NodeListType) ||
		null
);
// 是否隐藏全部行为
const hideAll = computed<boolean>(
	() =>
		((props.configInfo?.studentBehavior as Record<string, unknown>)?.hideAll as boolean) || false
);

// 休息时间标记点列表
const breakTimeMarkers = ref<BreakTimeMarker[]>([]);

watch(
	() => props.lessonInfo,
	(val) => {
		if (val && !hideAll.value) {
			nextTick(() => {
				getAILessonBehaviorStat();
			});
		}
	},
	{ immediate: true }
);

watch(
	() => props.lessonBehaviorDetail,
	(val) => {
		if (val && val.length && !hideAll.value) {
			nextTick(() => {
				initTrendChart();
			});
		}
	},
	{ immediate: true }
);

// 窗口大小与1920的比值
const rate = ref(
	(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) / 1920
);

onMounted(() => {
	window.addEventListener('resize', resizeHandler);
});

onUnmounted(() => {
	window.removeEventListener('resize', resizeHandler);
	if (lessonBehaviorChart.value) {
		lessonBehaviorChart.value.dispose();
	}
	if (behaviorChart.value) {
		behaviorChart.value.dispose();
	}
	if (activationChart.value) {
		activationChart.value.dispose();
	}
});

const resizeHandler = () => {
	setTimeout(() => {
		rate.value =
			(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) /
			1920;
		initLessonBehaviorPieChart();
		initLessonBehaviorBarChart();
		initTrendChart();
	}, 300);
};

// 计算休息时间标记线的位置
const calculateBreakTimeMarkers = () => {
	if (!activationChart.value || !props.realBreakTimeArr?.length) {
		breakTimeMarkers.value = [];
		return;
	}

	const markers: BreakTimeMarker[] = [];

	// 获取课程开始时间（使用videoBeginTime作为基准）
	const courseStartTime = props.videoBeginTime;

	// 获取grid配置
	const option = activationChart.value.getOption() as Record<string, unknown>;
	const gridOption = (option.grid as Array<Record<string, unknown>>)?.[0];
	if (!gridOption) return;

	const chartDom = document.querySelector('.trend-chart') as HTMLElement;
	if (!chartDom) return;

	const chartRect = chartDom.getBoundingClientRect();
	const chartHeight = chartRect.height;

	// 计算grid的实际像素位置
	const gridTop = gridOption.top as number;
	const gridBottom = gridOption.bottom as number;

	const gridHeight = chartHeight - gridTop - gridBottom;

	// 获取x轴的数据列表
	const xAxisData = props.lessonBehaviorDetail?.map((item) => item.orders * props.stepTime) || [];
	if (xAxisData.length === 0) return;

	props.realBreakTimeArr.forEach((item) => {
		// 处理开始休息标记
		if (item.startTime) {
			const minutesFromStart = (item.startTime - courseStartTime) / 1000 / 60;
			const pixelX = calculatePixelPosition(minutesFromStart, xAxisData);

			if (pixelX !== null) {
				markers.push({
					left: pixelX,
					top: gridTop,
					height: gridHeight,
					label: '休息',
					labelTop: gridHeight + 20 * rate.value
				});
			}
		}

		// 处理结束休息标记
		if (item.endTime) {
			const minutesFromStart = (item.endTime - courseStartTime) / 1000 / 60;
			const pixelX = calculatePixelPosition(minutesFromStart, xAxisData);

			if (pixelX !== null) {
				markers.push({
					left: pixelX,
					top: gridTop,
					height: gridHeight,
					label: '',
					labelTop: gridHeight + 20 * rate.value
				});
			}
		}
	});

	breakTimeMarkers.value = markers;
};

// 计算精确的像素位置（支持在两个x轴刻度之间）
const calculatePixelPosition = (targetMinutes: number, xAxisData: number[]): number | null => {
	if (!activationChart.value) return null;

	try {
		// 找到目标时间应该在哪两个刻度之间
		let leftIndex = -1;
		let rightIndex = -1;

		for (let i = 0; i < xAxisData.length; i++) {
			if (xAxisData[i] <= targetMinutes) {
				leftIndex = i;
			}
			if (xAxisData[i] >= targetMinutes && rightIndex === -1) {
				rightIndex = i;
				break;
			}
		}

		// 如果目标时间正好在某个刻度上
		if (leftIndex !== -1 && xAxisData[leftIndex] === targetMinutes) {
			const pixelPoint = activationChart.value.convertToPixel('grid', [leftIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}

		// 如果目标时间在两个刻度之间
		if (leftIndex !== -1 && rightIndex !== -1 && leftIndex !== rightIndex) {
			const leftPixel = activationChart.value.convertToPixel('grid', [leftIndex, 0]);
			const rightPixel = activationChart.value.convertToPixel('grid', [rightIndex, 0]);

			if (leftPixel && rightPixel && Array.isArray(leftPixel) && Array.isArray(rightPixel)) {
				// 计算目标时间在两个刻度之间的比例
				const ratio =
					(targetMinutes - xAxisData[leftIndex]) / (xAxisData[rightIndex] - xAxisData[leftIndex]);
				// 根据比例计算精确的像素位置
				const pixelX = leftPixel[0] + (rightPixel[0] - leftPixel[0]) * ratio;
				return pixelX;
			}
		}

		// 如果目标时间在最左边之前
		if (leftIndex === -1 && rightIndex !== -1) {
			const pixelPoint = activationChart.value.convertToPixel('grid', [rightIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}

		// 如果目标时间在最右边之后
		if (leftIndex !== -1 && rightIndex === -1) {
			const pixelPoint = activationChart.value.convertToPixel('grid', [leftIndex, 0]);
			return pixelPoint ? pixelPoint[0] : null;
		}
	} catch (e) {
		console.warn('计算像素位置失败:', e);
	}

	return null;
};

// 课堂行为统计数据
const AILessonBehaviorStat = ref<AILessonBehaviorStatType>({});
// 查询指定课堂行为统计数据
const getAILessonBehaviorStat = async () => {
	try {
		const data = await getAILessonBehaviorStatAPI(props.lessonInfo?.code as string);

		// 计算行为总次数
		let _totalCount = 0;
		data.forEach((item) => {
			if (
				item.behaviorType !== 'attend' &&
				item.num &&
				(!configList.value || configList.value[item.behaviorType]?.show)
			) {
				_totalCount += item.num;
			}
		});
		AILessonBehaviorStat.value = {};
		data.forEach((item) => {
			if (item.behaviorType !== 'attend') {
				if (item.num) {
					const _rate = Math.round((item.num * 100) / _totalCount);
					AILessonBehaviorStat.value[item.behaviorType] = {
						num: item.num,
						rate: _rate
					};
				} else {
					AILessonBehaviorStat.value[item.behaviorType] = {
						num: 0,
						rate: 0
					};
				}
			}
		});
		if (AILessonBehaviorStat.value) {
			nextTick(() => {
				initLessonBehaviorPieChart();
				initLessonBehaviorBarChart();
			});
		}
	} catch (err) {
		console.error(getErrorMessage(err));
	}
};

// 行为列表
const behaviorList = ref<BehaviorStatItemType[]>([
	{
		name: '课堂读写',
		behavior: 'readAndWrite',
		itemStyle: { color: '#00A8FF' }
	},
	{
		name: '课堂阅读',
		behavior: 'read',
		itemStyle: { color: '#59A3FF' }
	},
	{
		name: '课堂书写',
		behavior: 'write',
		itemStyle: { color: '#F78312' }
	},
	{
		name: '抬头听讲',
		behavior: 'normal',
		itemStyle: { color: '#2BDF59' }
	},
	{
		name: '课堂测验',
		behavior: 'test',
		itemStyle: { color: '#DEB7B1' }
	},
	{
		name: '举手',
		behavior: 'hand',
		itemStyle: { color: '#33D6EE' }
	},
	{
		name: '起立',
		behavior: 'stand',
		itemStyle: { color: '#D76AFF' }
	},
	{
		name: '趴桌子',
		behavior: 'sleep',
		itemStyle: { color: '#FFD200' }
	},
	{
		name: '使用手机',
		behavior: 'phone',
		itemStyle: { color: '#C1DAE7' }
	},
	{
		name: '低头',
		behavior: 'bowingTheHead',
		itemStyle: { color: '#B982C8' }
	},
	{
		name: '交头接耳',
		behavior: 'turnBack',
		itemStyle: { color: '#7A8ADB' }
	}
]);

// echarts对象
const lessonBehaviorChart = shallowRef<echarts.ECharts | null>(null);
// 初始化课堂行为统计饼图
const initLessonBehaviorPieChart = () => {
	// 整理数据
	let _data: BehaviorStatItemType[] = [];
	behaviorList.value.forEach((item) => {
		if (!configList.value || configList.value[item.behavior]?.show) {
			_data.push({
				behavior: item.behavior,
				name: item.name,
				value: AILessonBehaviorStat.value[item.behavior]?.rate || 0,
				itemStyle: item.itemStyle
			});
		}
	});

	_data = roundArrayWithSum(
		_data.map((item) => item.value || 0),
		0,
		100
	).map((item, index) => ({
		behavior: _data[index].behavior,
		name: _data[index].name,
		value: item,
		itemStyle: _data[index].itemStyle
	}));

	// 如果没有数据，不走下面
	if (
		!AILessonBehaviorStat.value?.readAndWrite?.rate &&
		!AILessonBehaviorStat.value?.read?.rate &&
		!AILessonBehaviorStat.value?.write?.rate &&
		!AILessonBehaviorStat.value?.normal?.rate &&
		!AILessonBehaviorStat.value?.hand?.rate &&
		!AILessonBehaviorStat.value?.stand?.rate &&
		!AILessonBehaviorStat.value?.sleep?.rate &&
		!AILessonBehaviorStat.value?.phone?.rate &&
		!AILessonBehaviorStat.value?.test?.rate &&
		!AILessonBehaviorStat.value?.bowingTheHead?.rate &&
		!AILessonBehaviorStat.value?.turnBack?.rate
	) {
		return;
	}

	if (lessonBehaviorChart.value) {
		lessonBehaviorChart.value.dispose();
	}
	lessonBehaviorChart.value = echarts.init(document.querySelector('.pie-chart') as HTMLElement);
	const option = {
		tooltip: {
			formatter: '{b}：{c}%',
			textStyle: {
				fontSize: 14 * rate.value,
				fontFamily: 'Alibaba PuHuiTi'
			}
		},
		legend: {
			height: 150 * rate.value,
			orient: 'vertical',
			right: 10 * rate.value,
			itemGap: 13 * rate.value,
			itemWidth: 11 * rate.value,
			itemHeight: 7 * rate.value,
			inactiveBorderWidth: 0,
			itemStyle: {
				borderWidth: 0
			},
			top: 'middle',
			data: _data.map((item) => item.name),
			formatter: (name: string) => {
				let _name = '';
				switch (name) {
					case '课堂读写':
						_name = `{a|${name}}\r\r{j|${
							_data.find((item) => item.behavior === 'readAndWrite')?.value || 0
						}%}`;
						break;
					case '课堂阅读':
						_name = `{a|${name}}\r\r{b|${
							_data.find((item) => item.behavior === 'read')?.value || 0
						}%}`;
						break;
					case '课堂书写':
						_name = `{a|${name}}\r\r{c|${
							_data.find((item) => item.behavior === 'write')?.value || 0
						}%}`;
						break;
					case '抬头听讲':
						_name = `{a|${name}}\r\r{d|${
							_data.find((item) => item.behavior === 'normal')?.value || 0
						}%}`;
						break;
					case '课堂测验':
						_name = `{a|${name}}\r\r{i|${
							_data.find((item) => item.behavior === 'test')?.value || 0
						}%}`;
						break;
					case '举手':
						_name = `{z|${name}}\r\r{e|${
							_data.find((item) => item.behavior === 'hand')?.value || 0
						}%}`;
						break;
					case '起立':
						_name = `{z|${name}}\r\r{f|${
							_data.find((item) => item.behavior === 'stand')?.value || 0
						}%}`;
						break;
					case '趴桌子':
						_name = `{z|${name}}\r\r{g|${
							_data.find((item) => item.behavior === 'sleep')?.value || 0
						}%}`;
						break;
					case '使用手机':
						_name = `{z|${name}}\r\r{h|${
							_data.find((item) => item.behavior === 'phone')?.value || 0
						}%}`;
						break;
					case '低头':
						_name = `{z|${name}}\r\r{k|${
							_data.find((item) => item.behavior === 'bowingTheHead')?.value || 0
						}%}`;
						break;
					default:
						_name = `{z|${name}}\r\r{l|${
							_data.find((item) => item.behavior === 'turnBack')?.value || 0
						}%}`;
				}
				return _name;
			},
			textStyle: {
				fontWeight: 400,
				lineHeight: 20 * rate.value,
				rich: {
					a: {
						fontSize: 12 * rate.value,
						fontFamily: 'Alibaba PuHuiTi',
						color: '#222222',
						width: 60 * rate.value
					},
					z: {
						fontSize: 12 * rate.value,
						fontFamily: 'Alibaba PuHuiTi',
						color: '#222222',
						width: 60 * rate.value
					},
					b: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#59A3FF'
					},
					c: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#F78312'
					},
					d: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#2BDF59'
					},
					e: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#33D6EE'
					},
					f: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#D76AFF'
					},
					g: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#FFD200'
					},
					h: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#C1DAE7'
					},
					i: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#DEB7B1'
					},
					j: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#00A8FF'
					},
					k: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#B982C8'
					},
					l: {
						fontSize: 16 * rate.value,
						fontFamily: 'Pangmen Title',
						color: '#7A8ADB'
					}
				}
			}
		},
		graphic: {
			type: 'text',
			left: 44 * rate.value,
			top: 'center',
			style: {
				text: '学生\n行为占比',
				textAlign: 'center',
				font: `400 ${14 * rate.value}px "Alibaba PuHuiTi"`,
				lineHeight: 18 * rate.value,
				fill: '#666666'
			}
		},
		series: [
			{
				name: '',
				type: 'pie',
				radius: ['45%', '70%'],
				center: [String(70 * rate.value), '50%'], // 修改为居中
				label: {
					show: false
				},
				minAngle: 8,
				itemStyle: {
					borderColor: '#ffffff',
					borderWidth: 2 * rate.value
				},
				emphasis: {
					itemStyle: {
						color: 'inherit'
					}
				},
				data: _data
			}
		]
	};
	lessonBehaviorChart.value.setOption(option);
};

// echarts对象
const behaviorChart = shallowRef<echarts.ECharts | null>(null);
// 初始化课堂行为统计柱状图
const initLessonBehaviorBarChart = () => {
	// 基于准备好的dom，初始化echarts实例
	const _xAxisList: string[] = [];
	const _yAxisList: number[] = [];
	behaviorList.value.forEach((item) => {
		if (!configList.value || configList.value[item.behavior]?.show) {
			_xAxisList.push(item.name);
			_yAxisList.push(AILessonBehaviorStat.value[item.behavior]?.num || 0);
		}
	});
	// 如果没有数据，不走下面
	if (
		!AILessonBehaviorStat.value?.readAndWrite?.num &&
		!AILessonBehaviorStat.value?.read?.num &&
		!AILessonBehaviorStat.value?.write?.num &&
		!AILessonBehaviorStat.value?.normal?.num &&
		!AILessonBehaviorStat.value?.test?.num &&
		!AILessonBehaviorStat.value?.hand?.num &&
		!AILessonBehaviorStat.value?.stand?.num &&
		!AILessonBehaviorStat.value?.sleep?.num &&
		!AILessonBehaviorStat.value?.phone?.num &&
		!AILessonBehaviorStat.value?.bowingTheHead?.num &&
		!AILessonBehaviorStat.value?.turnBack?.num
	) {
		return;
	}

	if (behaviorChart.value) {
		behaviorChart.value.dispose();
	}
	behaviorChart.value = echarts.init(document.querySelector('.bar-chart') as HTMLElement);
	const cWidth =
		window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
	const option = {
		grid: {
			left: 60 * rate.value,
			right: 30 * rate.value,
			top: 40 * rate.value,
			bottom: 40 * rate.value
		},
		tooltip: {
			textStyle: {
				fontSize: 14 * rate.value,
				fontFamily: 'Alibaba PuHuiTi'
			}
		},
		xAxis: {
			data: _xAxisList,
			nameTextStyle: {
				color: 'transparent'
			},
			axisLabel: {
				margin: 12 * rate.value,
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666',
				interval: 0,
				rotate: cWidth >= 1640 ? 0 : 25
			},
			axisTick: {
				length: 3 * rate.value,
				alignWithLabel: true,
				interval: 0,
				lineStyle: {
					color: '#E3E3E3'
				}
			},
			axisLine: {
				lineStyle: {
					color: '#E3E3E3'
				}
			}
		},
		yAxis: {
			name: '次数',
			minInterval: 1,
			nameTextStyle: {
				padding: [0, 30 * rate.value, 0, 0],
				fontSize: 12 * rate.value,
				fontFamily: 'Alibaba PuHuiTi',
				fontWeight: 400,
				color: '#666666'
			},
			axisLabel: {
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666'
			},
			splitLine: {
				lineStyle: {
					color: ['#EFEFEF']
				}
			}
		},
		series: [
			{
				type: 'bar',
				barWidth: 14 * rate.value,
				label: {
					show: true,
					position: 'top',
					fontSize: 12 * rate.value,
					fontWeight: 400,
					fontFamily: 'Alibaba PuHuiTi',
					color: '#666666'
				},
				itemStyle: {
					color: 'rgba(0, 168, 255, 0.63)'
				},
				data: _yAxisList
			}
		]
	};
	// 如果最大值小于5，设置y轴最大值为5
	const max = Math.max(..._yAxisList);
	if (max <= 5) {
		(option.yAxis as Record<string, unknown>).max = 5;
	}
	behaviorChart.value.setOption(option);
};

// echarts对象
const activationChart = shallowRef<echarts.ECharts | null>(null);
// 初始化课堂行为走势折线图
const initTrendChart = () => {
	// 整理数据
	const _xAxisList: number[] =
		props.lessonBehaviorDetail?.map((item) => item.orders * props.stepTime) || [];
	const _series: Record<string, unknown>[] = [];
	// 添加默认字段
	for (let i = 0; i < 11; i++) {
		let _name = '';
		let _color = '';
		let _behavior = '';
		switch (i) {
			case 0:
				_name = '课堂读写';
				_behavior = 'readAndWrite';
				_color = '#00A8FF';
				break;
			case 1:
				_name = '课堂阅读';
				_behavior = 'read';
				_color = '#59A3FF';
				break;
			case 2:
				_name = '课堂书写';
				_behavior = 'write';
				_color = '#F78312';
				break;
			case 3:
				_name = '抬头听讲';
				_behavior = 'normal';
				_color = '#2BDF59';
				break;
			case 4:
				_name = '课堂测验';
				_behavior = 'test';
				_color = '#DEB7B1';
				break;
			case 5:
				_name = '举手';
				_behavior = 'hand';
				_color = '#33D6EE';
				break;
			case 6:
				_name = '起立';
				_behavior = 'stand';
				_color = '#D76AFF';
				break;
			case 7:
				_name = '趴桌子';
				_behavior = 'sleep';
				_color = '#FFD200';
				break;
			case 8:
				_name = '使用手机';
				_behavior = 'phone';
				_color = '#C1DAE7';
				break;
			case 9:
				_name = '低头';
				_behavior = 'bowingTheHead';
				_color = '#B982C8';
				break;
			default:
				_name = '交头接耳';
				_behavior = 'turnBack';
				_color = '#7A8ADB';
		}
		if (!configList.value || configList.value[_behavior as NodeKeyType]?.show) {
			_series.push({
				name: _name,
				behavior: _behavior,
				type: 'line',
				smooth: true,
				triggerLineEvent: true,
				showAllSymbol: true,
				itemStyle: {
					color: _color,
					opacity: 0
				},
				lineStyle: {
					color: _color
				},
				emphasis: {
					focus: 'series',
					blurScope: 'coordinateSystem',
					lineStyle: {
						color: _color
					}
				},
				blur: {
					lineStyle: {
						opacity: 0
					}
				},
				data: []
			});
		}
	}
	props.lessonBehaviorDetail?.forEach((item: LessonBehaviorDetailItemType) => {
		let count0 = 0;
		let count1 = 0;
		let count2 = 0;
		let count3 = 0;
		let count4 = 0;
		let count5 = 0;
		let count6 = 0;
		let count7 = 0;
		let count8 = 0;
		let count9 = 0;
		let count10 = 0;
		item.behaviorData?.forEach((behavior) => {
			if (behavior.behaviorType === 'readAndWrite') {
				count0 += behavior.num;
			} else if (behavior.behaviorType === 'read') {
				count1 += behavior.num;
			} else if (behavior.behaviorType === 'write') {
				count2 += behavior.num;
			} else if (behavior.behaviorType === 'normal') {
				count3 += behavior.num;
			} else if (behavior.behaviorType === 'test') {
				count4 += behavior.num;
			} else if (behavior.behaviorType === 'hand') {
				count5 += behavior.num;
			} else if (behavior.behaviorType === 'stand') {
				count6 += behavior.num;
			} else if (behavior.behaviorType === 'sleep') {
				count7 += behavior.num;
			} else if (behavior.behaviorType === 'phone') {
				count8 += behavior.num;
			} else if (behavior.behaviorType === 'bowingTheHead') {
				count9 += behavior.num;
			} else if (behavior.behaviorType === 'turnBack') {
				count10 += behavior.num;
			}
		});
		_series.forEach((i) => {
			if (i.behavior === 'readAndWrite') {
				(i.data as number[]).push(count0);
			} else if (i.behavior === 'read') {
				(i.data as number[]).push(count1);
			} else if (i.behavior === 'write') {
				(i.data as number[]).push(count2);
			} else if (i.behavior === 'normal') {
				(i.data as number[]).push(count3);
			} else if (i.behavior === 'test') {
				(i.data as number[]).push(count4);
			} else if (i.behavior === 'hand') {
				(i.data as number[]).push(count5);
			} else if (i.behavior === 'stand') {
				(i.data as number[]).push(count6);
			} else if (i.behavior === 'sleep') {
				(i.data as number[]).push(count7);
			} else if (i.behavior === 'phone') {
				(i.data as number[]).push(count8);
			} else if (i.behavior === 'bowingTheHead') {
				(i.data as number[]).push(count9);
			} else if (i.behavior === 'turnBack') {
				(i.data as number[]).push(count10);
			}
		});
	});

	if (activationChart.value) {
		activationChart.value.dispose();
	}
	// 基于准备好的dom，初始化echarts实例
	activationChart.value = echarts.init(document.querySelector('.trend-chart') as HTMLElement);
	const option = {
		tooltip: {
			formatter: (params: { dataIndex: number; data: number; seriesName: string }) => {
				return `${params.dataIndex * props.stepTime}min：${params.data}人${params.seriesName}`;
			},
			textStyle: {
				fontSize: 14 * rate.value,
				fontFamily: 'Alibaba PuHuiTi'
			}
		},
		legend: {
			orient: 'vertical',
			right: 20 * rate.value,
			itemGap: 12 * rate.value,
			itemWidth: 11 * rate.value,
			itemHeight: 7 * rate.value,
			top: 'middle',
			data: _series.map((item) => item.name),
			textStyle: {
				fontSize: 12 * rate.value,
				fontFamily: 'Alibaba PuHuiTi',
				fontWeight: 400,
				color: '#222222'
			}
		},
		grid: {
			left: 55 * rate.value,
			right: 110 * rate.value,
			top: 30 * rate.value,
			bottom: props.realBreakTimeArr?.length ? 45 * rate.value : 40 * rate.value
		},
		xAxis: {
			name: '',
			data: _xAxisList,
			boundaryGap: false, // x轴两边不留空白
			nameTextStyle: {
				color: 'transparent'
			},
			axisLabel: {
				margin: 8 * rate.value,
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666',
				formatter: (name: string) => {
					return `${name}min`;
				}
			},
			axisTick: {
				length: 3 * rate.value,
				lineStyle: {
					color: '#E3E3E3'
				}
			},
			axisLine: {
				lineStyle: {
					color: '#E3E3E3'
				}
			}
		},
		yAxis: {
			name: '',
			minInterval: 1,
			nameTextStyle: {
				color: 'transparent'
			},
			axisLabel: {
				fontSize: 12 * rate.value,
				fontWeight: 400,
				fontFamily: 'Alibaba PuHuiTi',
				color: '#666666'
			},
			splitLine: {
				lineStyle: {
					color: ['#EFEFEF']
				}
			}
		},
		series: _series
	};
	activationChart.value.setOption(option);

	// 图表渲染完成后计算标记线位置
	nextTick(() => {
		// 等待echarts完全渲染
		setTimeout(() => {
			calculateBreakTimeMarkers();
		}, 100);
	});

	activationChart.value.on('click', (params) => {
		if (params.data) {
			const _behaviorDetail = props.lessonBehaviorDetail?.[params.dataIndex];
			if (_behaviorDetail && _behaviorDetail.behaviorData && _behaviorDetail.behaviorData.length) {
				if (params.seriesName === '课堂读写') {
					previewShow(_behaviorDetail, 'readAndWrite', '课堂读写');
				} else if (params.seriesName === '课堂阅读') {
					previewShow(_behaviorDetail, 'read', '课堂阅读');
				} else if (params.seriesName === '课堂书写') {
					previewShow(_behaviorDetail, 'write', '课堂书写');
				} else if (params.seriesName === '抬头听讲') {
					previewShow(_behaviorDetail, 'normal', '抬头听讲');
				} else if (params.seriesName === '课堂测验') {
					previewShow(_behaviorDetail, 'test', '课堂测验');
				} else if (params.seriesName === '举手') {
					previewShow(_behaviorDetail, 'hand', '举手');
				} else if (params.seriesName === '起立') {
					previewShow(_behaviorDetail, 'stand', '起立');
				} else if (params.seriesName === '趴桌子') {
					previewShow(_behaviorDetail, 'sleep', '趴桌子');
				} else if (params.seriesName === '使用手机') {
					previewShow(_behaviorDetail, 'phone', '使用手机');
				} else if (params.seriesName === '低头') {
					previewShow(_behaviorDetail, 'bowingTheHead', '低头');
				} else if (params.seriesName === '交头接耳') {
					previewShow(_behaviorDetail, 'turnBack', '交头接耳');
				}
			}
		}
	});
	// 鼠标移入时显示小圆点
	activationChart.value.on('mouseover', 'series', (params) => {
		const _option = activationChart.value?.getOption();
		if (_option?.series && (_option.series as Record<string, unknown>[]).length) {
			const _item = (_option.series as Record<string, unknown>[]).find(
				(item: Record<string, unknown>) => item.name === params.seriesName
			);
			if (_item) {
				(_item.itemStyle as Record<string, unknown>).opacity = 1;
			}
		}
		if (_option) {
			activationChart.value?.setOption(_option);
		}
	});
	// 鼠标移出时隐藏小圆点
	activationChart.value.on('mouseout', 'series', (params) => {
		const _option = activationChart.value?.getOption();
		if (_option?.series && (_option.series as Record<string, unknown>[]).length) {
			const _item = (_option.series as Record<string, unknown>[]).find(
				(item: Record<string, unknown>) => item.name === params.seriesName
			);
			if (_item) {
				(_item.itemStyle as Record<string, unknown>).opacity = 0;
			}
		}
		if (_option) {
			activationChart.value?.setOption(_option);
		}
	});
};

// 预览信息
const previewInfo = ref<PreviewInfoType | null>(null);
// 显示图片
const previewShow = (
	behaviorDetail: LessonBehaviorDetailItemType,
	type: NodeKeyType,
	name: string
) => {
	const _data = behaviorDetail.behaviorData.filter((item: BehaviorDataItemType) => {
		// 计算每张图片对应的视频时间
		if (item.occurTime) {
			const _occurTime = new Date(item.occurTime).getTime();
			item.videoTime =
				_occurTime - props.videoBeginTime > 0 ? (_occurTime - props.videoBeginTime) / 1000 - 1 : 0;
		}
		return item.behaviorType === type;
	});
	if (_data) {
		previewInfo.value = {
			transFileUrl: _data,
			name,
			type: 2,
			analysisType: 2 // 1:老师 2:学生
		};
		emit('previewShow', previewInfo.value);
	}
};
</script>

<style lang="scss" scoped>
.behavior-action-wrapper {
	margin-top: 1.6rem;

	.little-title {
		margin-top: 1.5rem;
		margin-bottom: 0.5rem;
		font-size: $font-size-base;
	}

	.behavior-rate {
		.chart-wrap {
			display: flex;
			gap: 2rem;

			.title-wrap {
				padding: 1.8rem 0 0 2.6rem;
				display: flex;
				align-items: center;

				.line {
					margin-right: 0.8rem;
					width: 0.4rem;
					height: $font-size-small-1;
					background: $color-brand;
					border-radius: 0.2rem;
				}

				p {
					font-size: $font-size-base;
					color: $text-color-brand;
				}
			}

			.pie-chart-wrap {
				flex: 1;
				min-width: 0;
				background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);

				.pie-chart,
				.empty {
					position: relative;
					width: 100%;
					height: 16.5rem;
				}
			}
			.bar-chart-wrap {
				flex: 1;
				min-width: 0;
				background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);

				.bar-chart,
				.empty {
					position: relative;
					width: 100%;
					height: 16.5rem;
				}
			}
		}
	}

	.behavior-trend {
		.trend-chart-container {
			position: relative;
			height: 25rem;
			background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);

			.trend-chart {
				position: relative;
				width: 100%;
				height: 100%;
			}

			// 休息时间标记线
			.break-time-marker {
				position: absolute;
				width: 0.2rem;
				background-color: rgba($color: $color-success, $alpha: 0.3);
				pointer-events: none;
				z-index: 10;

				.marker-label {
					position: absolute;
					left: 50%;
					transform: translateX(-50%);
					font-size: $font-size-small-2;
					color: $text-color-success;
					font-weight: bold;
					white-space: nowrap;
					padding: 0.2rem 0.4rem;
				}
			}
		}

		.empty {
			position: relative;
			height: 25rem;
			background-color: rgba($color: $bg-block-color-primary, $alpha: 0.9);
		}
	}
}
</style>
